package com.wangliang.deepseek.ui;

import com.intellij.ui.JBColor;
import com.intellij.util.ui.JBUI;
import lombok.extern.slf4j.Slf4j;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.net.URI;
import java.awt.Desktop;

@Slf4j
public class ChatMessagePanel extends JPanel {
    private static final int BUBBLE_ARC = 15;
    private static final int BUBBLE_PADDING = 15;
    private static final int MAX_WIDTH = 600; // 最大宽度
    private static final int AVATAR_SIZE = 32; // 头像大小

    private final String role;
    private final String message;
    private final Color backgroundColor;
    private final Color textColor;

    public ChatMessagePanel(String role, String message) {
        this.role = role;
        this.message = message;
        setLayout(new BorderLayout(10, 0));
        setOpaque(false);
        setBorder(JBUI.Borders.empty(10, 15));

        // 设置不同角色的颜色方案
        if ("User".equals(role)) {
            backgroundColor = new Color(75, 110, 175);
            textColor = Color.WHITE;
        } else {
            backgroundColor = new Color(60, 63, 65);
            textColor = new Color(187, 187, 187);
        }

        // 添加头像
        JPanel avatarPanel = createAvatarPanel();
        add("User".equals(role) ? avatarPanel : Box.createHorizontalStrut(AVATAR_SIZE), BorderLayout.EAST);
        add("User".equals(role) ? Box.createHorizontalStrut(AVATAR_SIZE) : avatarPanel, BorderLayout.WEST);

        // 添加消息内容
        JPanel contentPanel = createContentPanel();
        add(contentPanel, BorderLayout.CENTER);
    }

    private JPanel createAvatarPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 绘制圆形头像背景
                g2.setColor("User".equals(role) ? new Color(75, 110, 175) : new Color(100, 100, 100));
                g2.fillOval(0, 0, AVATAR_SIZE, AVATAR_SIZE);

                // 绘制头像文字
                g2.setColor(Color.WHITE);
                g2.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
                String initial = "User".equals(role) ? "U" : "A";
                FontMetrics fm = g2.getFontMetrics();
                int x = (AVATAR_SIZE - fm.stringWidth(initial)) / 2;
                int y = ((AVATAR_SIZE - fm.getHeight()) / 2) + fm.getAscent();
                g2.drawString(initial, x, y);

                g2.dispose();
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(AVATAR_SIZE, AVATAR_SIZE);
            }
        };
        panel.setOpaque(false);
        return panel;
    }

    private JPanel createContentPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(backgroundColor);

                // 创建带有尖角的气泡形状
                int arrowSize = 8;
                int x = "User".equals(role) ? 0 : arrowSize;
                int width = getWidth() - arrowSize;

                // 主体气泡
                RoundRectangle2D bubble = new RoundRectangle2D.Float(
                        x, 0, width - arrowSize, getHeight() - 1,
                        BUBBLE_ARC, BUBBLE_ARC);
                g2.fill(bubble);

                // 绘制尖角
                int[] xPoints = new int[3];
                int[] yPoints = new int[3];
                if ("User".equals(role)) {
                    xPoints = new int[] { width - arrowSize, width, width - arrowSize };
                    yPoints = new int[] { 10, 10 + arrowSize, 10 + arrowSize * 2 };
                } else {
                    xPoints = new int[] { arrowSize, 0, arrowSize };
                    yPoints = new int[] { 10, 10 + arrowSize, 10 + arrowSize * 2 };
                }
                g2.fillPolygon(xPoints, yPoints, 3);

                g2.dispose();
            }
        };

        panel.setLayout(new BorderLayout());
        panel.setOpaque(false);
        panel.setBorder(new EmptyBorder(BUBBLE_PADDING, BUBBLE_PADDING, BUBBLE_PADDING, BUBBLE_PADDING));

        // 如果消息包含代码块，使用 Markdown 渲染
        if (message.contains("```")) {
            JEditorPane editorPane = createMarkdownEditorPane(message);
            JPanel wrapperPanel = new JPanel(new BorderLayout());
            wrapperPanel.setOpaque(false);
            wrapperPanel.add(editorPane);
            wrapperPanel.setPreferredSize(new Dimension(MAX_WIDTH, wrapperPanel.getPreferredSize().height));
            panel.add(wrapperPanel);
        } else {
            JTextArea textArea = new JTextArea(message);
            textArea.setWrapStyleWord(true);
            textArea.setLineWrap(true);
            textArea.setOpaque(false);
            textArea.setEditable(false);
            textArea.setForeground(textColor);
            textArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));

            // 设置最大宽度
            int preferredWidth = Math.min(MAX_WIDTH, textArea.getPreferredSize().width);
            textArea.setSize(preferredWidth, Short.MAX_VALUE);
            int preferredHeight = textArea.getPreferredSize().height;
            textArea.setPreferredSize(new Dimension(preferredWidth, preferredHeight));

            panel.add(textArea);
        }

        return panel;
    }

    private JEditorPane createMarkdownEditorPane(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        String html = renderer.render(document);

        String styleTemplate = "<html><head><style>" +
                "body { " +
                "    font-family: 'Microsoft YaHei', sans-serif; " +
                "    font-size: 14px; " +
                "    color: %s; " +
                "    margin: 0; " +
                "    padding: 0; " +
                "    max-width: " + (MAX_WIDTH - 40) + "px; " +
                "} " +
                ".code-block { " +
                "    position: relative; " +
                "    background-color: #2b2b2b; " +
                "    padding: 12px; " +
                "    border-radius: 6px; " +
                "    margin: 10px 0; " +
                "    font-family: 'JetBrains Mono', monospace; " +
                "    font-size: 13px; " +
                "} " +
                ".code-header { " +
                "    display: flex; " +
                "    justify-content: space-between; " +
                "    align-items: center; " +
                "    padding: 8px 12px; " +
                "    background-color: #1e1f22; " +
                "    border-top-left-radius: 6px; " +
                "    border-top-right-radius: 6px; " +
                "    border-bottom: 1px solid #393b3d; " +
                "    margin: -12px -12px 8px -12px; " +
                "} " +
                ".code-lang { " +
                "    color: #808080; " +
                "    font-size: 12px; " +
                "} " +
                ".code-actions { " +
                "    display: flex; " +
                "    gap: 8px; " +
                "} " +
                ".code-action-button { " +
                "    padding: 4px 8px; " +
                "    background-color: #4d4d4d; " +
                "    border-radius: 4px; " +
                "    color: #d4d4d4; " +
                "    cursor: pointer; " +
                "    font-size: 12px; " +
                "    border: none; " +
                "} " +
                ".code-action-button:hover { " +
                "    background-color: #5a5a5a; " +
                "} " +
                "pre { " +
                "    margin: 0; " +
                "    overflow-x: auto; " +
                "    font-size: 13px; " +
                "    line-height: 1.4; " +
                "} " +
                "code { " +
                "    color: #a9b7c6; " +
                "} " +
                "p { margin: 0 0 10px 0; } " +
                "</style>" +
                "<script>" +
                "function copyCode(blockId) { " +
                "    const codeBlock = document.getElementById(blockId); " +
                "    const code = codeBlock.textContent; " +
                "    navigator.clipboard.writeText(code); " +
                "    const button = document.querySelector(`#${blockId}-copy`); " +
                "    button.textContent = '已复制'; " +
                "    setTimeout(() => button.textContent = '复制', 2000); " +
                "} " +
                "</script>" +
                "</head><body>%s</body></html>";

        // 处理代码块，添加头部和操作按钮
        String processedHtml = html.replaceAll(
                "<pre><code class=\"language-([^\"]+)\">([^<]+)</code></pre>",
                "<div class=\"code-block\">" +
                        "<div class=\"code-header\">" +
                        "<span class=\"code-lang\">$1</span>" +
                        "<div class=\"code-actions\">" +
                        "<button class=\"code-action-button\" id=\"code-$1-copy\" " +
                        "onclick=\"copyCode('code-$1')\">复制</button>" +
                        "</div>" +
                        "</div>" +
                        "<pre><code id=\"code-$1\" class=\"language-$1\">$2</code></pre>" +
                        "</div>");

        html = String.format(styleTemplate,
                String.format("#%06x", textColor.getRGB() & 0xFFFFFF),
                processedHtml);

        JEditorPane editorPane = new JEditorPane("text/html", html);
        editorPane.setEditable(false);
        editorPane.setOpaque(false);
        editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
        editorPane.addHyperlinkListener(e -> {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                    Desktop.getDesktop().browse(e.getURL().toURI());
                } catch (Exception ex) {
                    log.error("Failed to open URL", ex);
                }
            }
        });

        return editorPane;
    }
}